package br.com.lumis.saas.service.consumerclient.postloadprocessor;

import lumis.doui.source.ISourceData;
import lumis.doui.source.Source;
import lumis.doui.source.TabularData;
import lumis.doui.source.TabularSource;
import lumis.doui.source.postloadprocessor.IPostLoadProcessor;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.util.ITransaction;

import org.w3c.dom.Node;

import br.com.lumis.saas.SaasRequestParameters;
import br.com.lumis.saas.service.consumerclient.model.Customer;
import br.com.lumis.saas.service.consumerclient.persistence.dao.CustomerDAO;
import br.com.lumis.saas.service.consumerclient.persistence.dao.EnvironmentDAO;

public class NameEnvironmentPostLoadProcessor implements IPostLoadProcessor {
	
	private CustomerDAO customerDAO = new CustomerDAO();
	private EnvironmentDAO environmentDAO = new EnvironmentDAO();
	@SuppressWarnings("unchecked")
	public void processSource(SessionConfig sessionConfig, Source source,
			Node parametersNode, ITransaction transaction)
			throws PortalException {

		
		TabularSource<?> tabularSource = (TabularSource<?>) source;
		TabularData tabularData = tabularSource.getData();
		
		if (tabularData.getRows().size() == 0)
			return;			

		for (ISourceData row : tabularData.getRows()) {				
			
			int type = row.get(SaasRequestParameters.TYPE, Integer.class);
			String environmentId = row.get("id", String.class);
			String name = row.get(SaasRequestParameters.PAGE_PARAMETER_NAME, String.class);
								
			Customer customer = customerDAO.getByName(row.get(SaasRequestParameters.PAGE_PARAMETER_CUSTOMERID, String.class), transaction);
			
			if(name==null){
				if(type==1)											
					name = "saas-"+customer.getSurname().toLowerCase() +"-app";
				else if(type==2) 
					name = "saas-"+customer.getSurname().toLowerCase() +"-dev";				
				else if(type==3){
					int sufix = row.get(SaasRequestParameters.SUFIX, Integer.class);
					name = "saas-"+customer.getSurname().toLowerCase() +"-app-" +sufix ;										
				}			
				environmentDAO.updateName(environmentId,  name,  transaction);
				row.put(SaasRequestParameters.PAGE_PARAMETER_NAME, name);
			}									
		}		
	}
}
